package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.SensorData;
import com.ny.repository.SensorDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/sensor")
public class SensorDataController {

    @Autowired
    private SensorDataRepository sensorDataRepository;

    /**
     * 获取最新的传感器数据
     * @return 最新的10条传感器数据
     */
    @GetMapping("/latest")
    public Result getLatestSensorData() {
        try {
            List<SensorData> latestData = sensorDataRepository.findAll();
            // 按接收时间倒序排列，获取最新的数据
            latestData.sort((s1, s2) -> s2.getReceiveTime().compareTo(s1.getReceiveTime()));
            // 只返回最新的10条记录
            if (latestData.size() > 10) {
                latestData = latestData.subList(0, 10);
            }
            return Result.success(latestData);
        } catch (Exception e) {
            return Result.error("获取传感器数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有传感器数据
     * @return 传感器数据列表
     */
    @GetMapping("/all")
    public Result getAllSensorData() {
        try {
            List<SensorData> sensorDataList = sensorDataRepository.findAll();
            // 按接收时间倒序排列
            sensorDataList.sort((s1, s2) -> s2.getReceiveTime().compareTo(s1.getReceiveTime()));
            return Result.success(sensorDataList);
        } catch (Exception e) {
            return Result.error("获取传感器数据失败: " + e.getMessage());
        }
    }

    /**
     * 根据设备ID获取传感器数据
     * @param deviceId 设备ID
     * @return 该设备的传感器数据列表
     */
    @GetMapping("/by-device")
    public Result getSensorDataByDeviceId(String deviceId) {
        try {
            List<SensorData> sensorDataList = sensorDataRepository.findAll();
            // 过滤指定设备的数据
            sensorDataList.removeIf(data -> !data.getDeviceId().equals(deviceId));
            // 按接收时间倒序排列
            sensorDataList.sort((s1, s2) -> s2.getReceiveTime().compareTo(s1.getReceiveTime()));
            return Result.success(sensorDataList);
        } catch (Exception e) {
            return Result.error("获取传感器数据失败: " + e.getMessage());
        }
    }
}